<template>
  <div class="hls-video-player">
    <video id="myVideo" controls muted preload="auto" :class="{ 'hide-progress': videoType === 'live' }"></video>
  </div>
</template>

<script>
export default {
  name: 'HlsPlayer',
  props: {
    videoType: {
      type: String,
      default: 'live'
    }
  },
  data() {
    return {
      hlsplayer: null
    }
  },
  beforeDestroy() {
    if (this.hlsplayer != null) {
      this.hlsplayer.destroy();
      this.hlsplayer = null;
    }
  },
  methods: {
    //创建hls播放器
    playHls(url) {
      //先触发销毁
      if (this.hlsplayer != null) {
        this.hlsplayer.destroy();
      }
      //创建播放
      let video = document.getElementById("myVideo");
      if (Hls.isSupported()) {
        this.hlsplayer = new Hls({
          xhrSetup: function (xhr, url) {
            // 修改请求的URL，例如更改域名
            // if(url.indexOf('.ts') != -1) {
            //   xhr.open('GET', url.replace('https://platform-wh.youdingte.com', 'https://10.2.8.11:7096'), true);
            // }
            // 提取.m3u8中的token，并添加到.ts请求中
            if (url.indexOf('.m3u8') != -1) {
              token = url.substring(url.indexOf('token=') + 6, url.length)
            }
            if (url.indexOf('.ts') != -1) {
              xhr.open('GET', url + '?token=' + token, true);
            }
          }
        });
        this.hlsplayer.loadSource(url);
        this.hlsplayer.attachMedia(video);
        this.hlsplayer.on(Hls.Events.MANIFEST_PARSED, function () {
          video.play();
        });
      } else if (video.canPlayType('application/vnd.apple.mpegurl')) {
        console.log("apple原生");
        // 如果支持原生播放
        video.src = url;
      }
    }
  }
}
</script>

<style scoped>
.hls-video-player {
  background-color: black;
}

/**
#dhHlsVdieoCloseBtnmyVideo {
  color: #409EFF !important;
  font-size: 23px !important;
}
*/

video {
  width: 100%;
  height: 34vh;
}

/* 隐藏进度条及当前时间和剩余时间 */
.hide-progress::-webkit-media-controls-timeline,
.hide-progress::-webkit-media-controls-current-time-display,
.hide-progress::-webkit-media-controls-time-remaining-display {
  display: none !important;
}
</style>